package com.endbd.systemmanagement.controller.address;


import com.endbd.feignapi.config.RedisConfig;
import com.endbd.feignapi.model.system.City;
import com.endbd.feignapi.model.system.Province;
import com.endbd.feignapi.model.warehouse.Warehouse;
import com.endbd.systemmanagement.service.address.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system")
public class AddressControl {

    @Autowired
    private IAddressService addressService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/cityList")
    public List<City> cityList(Integer provinceId) {
        Map<String, List<City>> cityMap = (Map<String, List<City>>) redisTemplate.opsForValue().get("cityMap");
        if (cityMap == null) {
            cityMap = new HashMap<>();
            redisTemplate.opsForValue().set("cityMap",cityMap);
        }

        List<City> cityList = cityMap.get(provinceId.toString());
        if (cityList == null) {
            Province province = new Province();
            province.setId(provinceId);
            cityList = addressService.cityList(province);
            cityMap.put(provinceId.toString(), cityList);
            redisTemplate.opsForValue().set("cityMap",cityMap);
        }
        return cityList;
    }

    @RequestMapping("/cityMap")
    public Map<Integer, List<City>> cityMap() {
        List<Province> provinceList = provinceList();
        Map<Integer, List<City>> cityMap = new HashMap<>();
        for (Province province : provinceList) {
            cityMap.put(province.getId(), cityList(province.getId()));
        }

        return cityMap;
    }

    @RequestMapping("/provinceList")
    public List<Province> provinceList() {
        List<Province> provinceList = (List<Province>) redisTemplate.opsForValue().get("provinceList");

        if (provinceList == null) {
            provinceList = addressService.provinceList();
            redisTemplate.opsForValue().set("provinceList", provinceList);
        }

        return provinceList;
    }

}
